package com.aiti.lulian.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardBusinessContractDto;
import com.aiti.lulian.dto.CommunicateInfoSaveDto;
import com.aiti.lulian.dto.CustomerContactsDto;
import com.aiti.lulian.dto.CustomerManagementDto;
import com.aiti.lulian.dto.crm.CrmFollowRecordDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.crm.CrmFollowRecord;
import com.aiti.lulian.entity.excel.CustomerManagementExcelImport;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.service.*;
import com.aiti.lulian.utils.DateFilterUtil;
import com.aiti.lulian.utils.MyStrUtil;
import com.aiti.lulian.vo.CustomerCollaboratorVo;
import com.aiti.lulian.vo.CustomerManagementVo;
import com.aiti.lulian.vo.CustomerTagVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CustomerManagementServiceImpl extends BaseSerivceImpl<CustomerManagementMapper, CustomerManagement> implements ICustomerManagementService {

    @Autowired
    private CustomerManagementMapper customerManagementMapper;

    @Autowired
    private ICustomerManagementService customerManagementService;

    @Autowired
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;

    @Autowired
    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;

    @Autowired
    private ICustomerContactsService customerContactsService;

    @Autowired
    private ICustomerTagRelationService customerTagRelationService;

    @Autowired
    private ICustomerCollaboratorService customerCollaboratorService;

    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Autowired
    private ICustomerContactsRelationService customerContactsRelationService;

    @Autowired
    private ICrmFollowRecordService crmFollowRecordService;

    @Autowired
    private ISysDataService sysDataService;

    @Autowired
    private IEnterpriseDictDataService enterpriseDictDataService;
    @Autowired
    private ICommunicateInfoService communicateInfoService;
    @Autowired
    private CardBusinessContractService cardBusinessContractService;
    @Autowired
    private CustomerFollowUpRecordMapper customerFollowUpRecordMapper;
    @Autowired
    private ILuLianEnterpriseUserService luLianEnterpriseUserService;
    @Autowired
    private ILuLianEnterpriseService enterpriseService;
    @Autowired
    private CardBusinessCollaboratorService cardBusinessCollaboratorService;



    @Override
    public List<CustomerManagementVo> findCustomerListPage(Page page, CustomerManagementDto customerManagementDto, String userId) {
        LuLianEnterpriseHistory lianEnterpriseHistory = luLianEnterpriseHistoryMapper.getEnterpriseIdAndNames(userId);
        if(lianEnterpriseHistory!=null){
            //公司id
            String companyId = lianEnterpriseHistory.getBaseId();
            return customerManagementMapper.findCustomerListPage(page, customerManagementDto,companyId);
        }
        return null;
    }

    @Override
    public CustomerManagementVo getCustomerById(String baseId) {
        CustomerManagementVo customerManagementVo = customerManagementMapper.selectCustomerById(baseId);

        List<CustomerContacts> customerContacts = customerContactsRelationService.getListByCustomerId(baseId);
        customerManagementVo.setCustomerContactsList(customerContacts);

        return customerManagementVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message addCustomer(CustomerManagementDto customerManagementDto) {
        CustomerManagement customerManagement = new CustomerManagement();
        BeanUtils.copyProperties(customerManagementDto, customerManagement);
        if (StrUtil.isNotBlank(customerManagement.getCreator())) {
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserQueryWrapper = new LambdaQueryWrapper<>();
            enterpriseUserQueryWrapper.eq(LuLianEnterpriseUser::getUserId, customerManagement.getCreator());
            LuLianEnterpriseUser luLianEnterpriseUser = luLianEnterpriseUserMapper.selectOne(enterpriseUserQueryWrapper);
            customerManagement.setCompanyId(luLianEnterpriseUser.getEnterpriseId());
        }
        boolean save = this.save(customerManagement);

//        List<CustomerContacts> customerContactsList = customerManagementDto.getCustomerContactsList();
//        List<CustomerContacts> collect = customerContactsList.stream().peek(contacts -> contacts.setCustomerId(customerManagement.getBaseId())).collect(Collectors.toList());
//        boolean saveBatch = customerContactsService.saveBatch(collect);
        if (save){
            return Message.success("新增成功");
        } else {
            return Message.fail("新增失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message updateCustomer(CustomerManagementDto customerManagementDto) {
        CustomerManagement customerManagement = new CustomerManagement();
        BeanUtils.copyProperties(customerManagementDto, customerManagement);

        boolean update = this.updateById(customerManagement);

//        LambdaQueryWrapper<CustomerContacts> contactsQueryWrapper = new LambdaQueryWrapper<>();
//        contactsQueryWrapper.eq(CustomerContacts::getCustomerId, customerManagementDto.getBaseId());
//        customerContactsService.remove(contactsQueryWrapper);
//        List<CustomerContacts> collect = customerManagementDto.getCustomerContactsList().stream().peek(contacts -> contacts.setCustomerId(customerManagement.getBaseId())).collect(Collectors.toList());
//        boolean saveBatch = customerContactsService.saveBatch(collect);

        if (update){
            return Message.success("修改成功");
        } else {
            return Message.fail("修改失败");
        }
    }

    @Override
    public int updateCustomerById(String baseId) {
        CustomerManagement customerManagement = customerManagementService.getById(baseId);
        customerManagement.setIsDel("1");
        int update = customerManagementMapper.updateById(customerManagement);
        if (update > 0){
            return 6;
        }
        return 0;
    }

    /***
     * 获取员工客户数量
     * @param enterpriseId 企业Id
     */
    @Override
    public List<Map> getCustomerCountByEmployee(Page<List<Map>> page,String enterpriseId,String userId) {
        //执行这里时enterpriseId非企业角色下会为空
        List<Map> resultMap = customerManagementMapper.getCustomerCountByEmployee(enterpriseId,userId);
        if(resultMap != null && !resultMap.isEmpty()){
            String userIds = resultMap.stream().map(k -> (String) k.get("employee")).collect(Collectors.joining(","));
            if(StringUtils.isNotBlank(userIds)){
                Message userList = cloudShowManagerSubService.getUserList(userIds);
                if(userList.getCode() == 1){
                    throw new RuntimeException("员工信息获取失败");
                }
                List<LinkedHashMap> userInfoList = (List<LinkedHashMap>)userList.getObj();
                if(userInfoList != null && !userInfoList.isEmpty()){
                    Map<String, String> userInfoMap = userInfoList.stream().collect(Collectors.toMap(k -> (String)k.get("baseId"), v -> v.get("nickname") != null ? (String)v.get("nickname"):(String)v.get("username")));
                    resultMap.forEach(item -> {
                        if(userInfoMap.containsKey(item.get("employee"))){
                            item.put("employee", userInfoMap.get(item.get("employee")));
                        }
                    });
                }
            }else{
                throw new RuntimeException("员工信息获取失败");
            }
        }
        return resultMap;
    }

    /***
     * 查询客户总数、成交客户、潜在客户
     * @param enterpriseId
     */
    @Override
    public Map getCustomTotal(String enterpriseId,String userId) {
        //非企业角色登陆enterpriseId会为空
        Map resultMap = customerManagementMapper.getCustomTotal(enterpriseId,userId);
        if(resultMap == null){
            resultMap = new HashMap<String,String>();
            resultMap.put("totalCount","0");
            resultMap.put("chengJiaoCount","0");
            resultMap.put("qianZaiCount","0");
            return resultMap;
        }
        return resultMap;
    }

    @Override
    public List<CustomerManagementVo> getCustomerList(CustomerManagementDto customerManagementDto, Page<CustomerManagementVo> page) {
        if (StrUtil.isNotBlank(customerManagementDto.getDateType())) {
            Map<String, DateTime> beginAndEnd = DateFilterUtil.getBeginAndEnd(customerManagementDto.getDateType());
            customerManagementDto.setBeginDate(beginAndEnd.get("begin"));
            customerManagementDto.setEndDate(beginAndEnd.get("end"));
        }

        if (StrUtil.isNotBlank(customerManagementDto.getCity()) && StrUtil.isBlank(customerManagementDto.getCounty())) {
            customerManagementDto.setProvince(null);
        } else if (StrUtil.isNotBlank(customerManagementDto.getCounty())) {
            customerManagementDto.setProvince(null);
            customerManagementDto.setCity(null);
        }

        //获取当前用户的权限
        String scope = null;
        Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(customerManagementDto.getUserId());
        if (userAccessScopeMessage == null) {
            throw new RuntimeException("获取用户访问权限失败");
        } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
            throw new RuntimeException("查询用户访问权限失败");
        } else {
            scope = (String) userAccessScopeMessage.getObj();
        }
        //判断该用户是否为企业管理员
        boolean enterpriseAdmin = StrUtil.equals(scope, "4");
        customerManagementDto.setEnterpriseAdmin(enterpriseAdmin);
            //查询该用户是否为部门负责人及其所属部门
            if(! enterpriseAdmin) {
                Message userInfoMessage = cloudShowManagerSubService.getUserInfo(customerManagementDto.getUserId());
                if (userInfoMessage == null) {
                    throw new RuntimeException("获取用户信息失败");
                } else if (! userInfoMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                    throw new RuntimeException("查询用户信息失败");
                } else {
                    Object obj = userInfoMessage.getObj();
                    if (obj == null) {
                        throw new RuntimeException("查询用户为空");
                    }
                    ObjectMapper mapper = new ObjectMapper();
                    Map userInfoMap = mapper.convertValue(obj, Map.class);
                    String deptPermission = (String) userInfoMap.get("deptPermission");
                    String deptId = (String) userInfoMap.get("deptId");
                    customerManagementDto.setDeptPermission(deptPermission);
//                    customerManagementDto.setDeptId(deptId);

                    //若为部门负责人，则获取其部门下所有子部门数据
                    if (StrUtil.equals(deptPermission, "1")) {
                        Message getSubDeptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                        if (getSubDeptMessage == null) {
                            throw new RuntimeException("获取子部门数据失败");
                        } else if (! getSubDeptMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                            throw new RuntimeException("查询子部门数据失败");
                        } else {
                            //获取到子部门以","分割的形式
                            String deptIds = (String) getSubDeptMessage.getObj();
                            if (deptIds == null) {
                                throw new RuntimeException("查询子部门数据为空");
                            }
                            List<String> deptIdList = new ArrayList<>(Arrays.asList(deptId));
                            if (StrUtil.isNotBlank(deptIds)) {
                                deptIdList.addAll(Arrays.asList(deptIds.split(",")));
                            }
                            customerManagementDto.setDeptIdList(deptIdList);
                        }
                    } else {
                        ;
                    }
                }
            } else {
                ;
            }
        Date dateBegin = customerManagementDto.getDateBegin();
        Date dateEnd = customerManagementDto.getDateEnd();
        if (dateBegin != null && dateEnd != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateEnd);
            calendar.add(Calendar.DATE, 1);
            customerManagementDto.setDateEnd(calendar.getTime());
        }
        //处理按部门作为条件查询的请求
        String deptIdCondition = customerManagementDto.getDeptId();
        if (StrUtil.isNotBlank(customerManagementDto.getDeptId())) {
            Message getSubDeptAnotherMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptIdCondition);
            if (getSubDeptAnotherMessage == null) {
                throw new RuntimeException("获取子部门数据失败");
            } else if (! getSubDeptAnotherMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                throw new RuntimeException("查询子部门数据失败");
            } else {
                //获取到子部门以","分割的形式
                String deptIds = (String) getSubDeptAnotherMessage.getObj();
                if (deptIds == null) {
                    throw new RuntimeException("查询子部门数据为空");
                }
                List<String> deptIdConditionList = new ArrayList<>(Arrays.asList(deptIdCondition));
                if (StrUtil.isNotBlank(deptIds)) {
                    deptIdConditionList.addAll(Arrays.asList(deptIds.split(",")));
                }
                customerManagementDto.setDeptIdConditionList(deptIdConditionList);
            }
        }
        List<CustomerManagementVo> customerManagementVos = customerManagementMapper.selectCustomerList(customerManagementDto, page);

        //遍历填充客户的联系人列表
        for (CustomerManagementVo customerManagementVo : customerManagementVos) {
            List<CustomerContacts> customerContacts = customerContactsService.getList(customerManagementVo.getBaseId());
            if (customerContacts.size() > 0) {
                customerManagementVo.setCustomerContactsList(customerContacts.subList(0, 1));
                CustomerContacts firstCustomerContacts = customerContacts.get(0);
                customerManagementVo.setCustomerContactsTelephone(firstCustomerContacts.getTelephone());
                customerManagementVo.setCustomerContactsPhone(firstCustomerContacts.getContactsPhone());
            } else {
                customerManagementVo.setCustomerContactsList(new ArrayList<>());
                customerManagementVo.setCustomerContactsTelephone("");
                customerManagementVo.setCustomerContactsPhone("");
            }
            String collaboratorsStr = customerManagementVo.getCollaborators().stream().map(CustomerCollaboratorVo::getRealname).collect(Collectors.joining(","));
            customerManagementVo.setCollaboratorsStr(collaboratorsStr);
            List<CustomerTagVo> tags = customerTagRelationService.getCustomerTagRelationList(customerManagementVo.getBaseId());
            customerManagementVo.setTags(tags);
            List<CustomerCollaboratorVo> collaborators = customerCollaboratorService.getCustomerCollaboratorList(customerManagementVo.getBaseId());
            customerManagementVo.setCollaborators(collaborators);
        }
        return customerManagementVos;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message removeCustomerByBaseIds(String[] baseIds) {
        List<String> strings = Arrays.asList(baseIds);
        for (String baseId : strings) {
            //删除客户联系人数据
//            customerContactsService.remove(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getCustomerId, baseId));
            customerContactsRelationService.remove(new LambdaQueryWrapper<CustomerContactsRelation>().eq(CustomerContactsRelation::getCustomerId, baseId));
            //删除客户标签数据
            customerTagRelationService.remove(new LambdaQueryWrapper<CustomerTagRelation>().eq(CustomerTagRelation::getCustomerId, baseId));
            //删除客户协作人数据
            customerCollaboratorService.remove(new LambdaQueryWrapper<CustomerCollaborator>().eq(CustomerCollaborator::getCustomerId, baseId));
        }
        //删除客户数据
        this.customerManagementMapper.deleteBatchIds(strings);
        return Message.success("删除成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message forwardCustomer(CustomerManagementDto customerManagementDto) {
        boolean updateBatchById = true;
        List<CustomerManagement> customerManagements = new ArrayList<>();
        for (String customerId : customerManagementDto.getCustomerIds()){
            CustomerManagement customerManagement = new CustomerManagement();
            customerManagement.setBaseId(customerId);
            customerManagement.setSaleResponsiblePerson(customerManagementDto.getSaleResponsiblePerson());
            customerManagement.setSaleResponsiblePersonName(customerManagementDto.getSaleResponsiblePersonName());
            customerManagement.setDeptId(customerManagementDto.getDeptId());
            customerManagement.setUpdateBy(customerManagementDto.getUserId());
            customerManagement.setBaseUpdateTime(new Date());
            customerManagement.setIsPublic(customerManagementDto.getIsPublic());
            if (StrUtil.equals(customerManagementDto.getIsPublic(), "1")) {
                //转移至公海
                customerManagement.setTurnInTime(new Date());
            }
            if (StrUtil.equals(customerManagementDto.getIsPublic(), "2")) {
                //从公海转出
                customerManagement.setIsPublic("0");
                customerManagement.setSaleResponsiblePerson(customerManagementDto.getUserId());
                customerManagement.setDeptId(customerManagementDto.getDeptId());
            }
            customerManagements.add(customerManagement);
            //判断转交的对象是否为当前客户的协作人，若是则移除该客户的该协作人，对该客户来说转交这一操作实现了身份从协作人到负责人的转变
            CustomerCollaborator collaborator = customerCollaboratorService.getOne(new LambdaQueryWrapper<CustomerCollaborator>().eq(CustomerCollaborator::getCustomerId, customerId).eq(CustomerCollaborator::getUserId, customerManagementDto.getSaleResponsiblePerson()));
            if (collaborator != null) {
                boolean remove = customerCollaboratorService.removeById(collaborator.getBaseId());
                if (! remove) {
                    updateBatchById = false;
                }
            }
        }
        if (updateBatchById) {
            updateBatchById = this.updateBatchById(customerManagements);
            if (updateBatchById) {
                return Message.success("转交成功");
            } else {
                return Message.fail("转交失败");
            }
        } else {
            return Message.fail("转交失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message saveCustomer(CustomerManagementDto customerManagementDto) {
        //校验当前企业的客户中是否已存在该客户名称的客户，若存在则无法新增
        List<CustomerManagement> list = this.list(new LambdaQueryWrapper<CustomerManagement>().eq(CustomerManagement::getEnterpriseName, customerManagementDto.getEnterpriseName().trim())
                .eq(CustomerManagement::getCompanyId, customerManagementDto.getCompanyId())
                .eq(CustomerManagement::getIsDel, "0"));
        if (list.size() > 0) {
            return Message.fail("该客户已存在");
        }
        String userId = customerManagementDto.getUserId();
        //保存客户数据
        CustomerManagement customerManagement = new CustomerManagement();
        BeanUtils.copyProperties(customerManagementDto, customerManagement);
        customerManagement.setCreator(userId);
        customerManagement.setBaseCreateTime(new Date());
        CrmFollowRecordDto followUpDto = customerManagementDto.getFollowUpRecord();
        if(followUpDto != null && followUpDto.getNextFollowTime() != null){
            Date nextFollowTime = followUpDto.getNextFollowTime();
            customerManagement.setNextFollowTime(nextFollowTime);
        }
        //对于未填写跟进状态的客户，将其客户类型自动归为潜在客户
        EnterpriseDictData enterpriseDictData = enterpriseDictDataService.getOne(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, customerManagementDto.getCompanyId())
                .eq(EnterpriseDictData::getBaseName, "潜在客户"));
        if (StrUtil.isBlank(customerManagementDto.getFollowStatus())) {
            if (enterpriseDictData != null) {
                customerManagement.setCustomerType(enterpriseDictData.getBaseId());
            } else {
                log.error("企业【{}】潜在客户字典项不存在，请及时处理");
            }
        }
        String followUpState = customerManagementDto.getFollowStatus();
        if(StringUtils.isEmpty(followUpState) && !enterpriseDictData.getBaseId().equals(customerManagementDto.getCustomerType())){
            return Message.success("请选择跟进状态");
        }
        Message message = cloudShowManagerSubService.getUserInfo(userId);
        if (message == null) {
            return Message.fail("获取用户信息失败！");
        }
        Object obj = message.getObj();
        if (obj == null) {
            return Message.fail("获取用户信息失败！");
        }
        if (message.getCode() == 1) {
            return Message.fail("查询用户信息错误");
        }
        ObjectMapper mapper = new ObjectMapper();
        Map resultMap = mapper.convertValue(obj, Map.class);
        String deptId = (String)resultMap.get("deptId");
        String deptName = (String)resultMap.get("deptName");
        String directorName = (String)resultMap.get("realname");
        String enterpriseId = (String)resultMap.get("companyId");
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(StringUtils.isEmpty(enterpriseId)){
            if(enterpriseUser != null){
                enterpriseId = enterpriseUser.getEnterpriseId();
                resultMap.put("companyId", enterpriseId);
            }else{
                return Message.fail("获取所选负责人企业信息失败！");
            }
        }
        Message validateMessage = validateInfo(customerManagementDto, enterpriseId);
        if(MessageCodeConstant.MSG_FAIL_CODE.equals(validateMessage.getCode())){
            return validateMessage;
        }
        boolean saveCustomer = this.save(customerManagement);


        if(!enterpriseDictData.getBaseId().equals(customerManagementDto.getCustomerType())){
            addOtherInfo(customerManagement, customerManagementDto, resultMap);
        }
        //联系人
        CustomerContactsDto contact = customerManagementDto.getContact();
        if(contact != null){
            int count = customerContactsService.count(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getContactsName, contact.getContactsName()).eq(CustomerContacts::getTelephone, contact.getTelephone()).eq(CustomerContacts::getEnterpriseId, enterpriseId));
            if(count <= 0){
                //新建联系人
                CustomerContacts customerContacts = new CustomerContacts();
                BeanUtils.copyProperties(contact, customerContacts);
                customerContacts.setEnterpriseId(enterpriseId);
                customerContacts.setDeptId(deptId);
                customerContacts.setDirectorName(directorName);
                customerContacts.setDeptName(deptName);
                customerContacts.setCreator(customerManagementDto.getUserId());
                customerContacts.setBaseCreateTime(new Date());
                customerContactsService.save(customerContacts);
                CustomerContactsRelation relation = new CustomerContactsRelation();
                relation.setContactId(customerContacts.getBaseId());
                relation.setCustomerId(customerManagement.getBaseId());
                customerContactsRelationService.save(relation);
            }

        }
        //保存客户与标签的关联关系
        List<CustomerTag> tags = customerManagementDto.getTags();
        if (tags != null && tags.size() > 0) {
            List<CustomerTagRelation> customerTagRelations = new ArrayList<>();
            for (CustomerTag tag : tags) {
                CustomerTagRelation customerTagRelation = new CustomerTagRelation();
                customerTagRelation.setCustomerId(customerManagement.getBaseId());
                customerTagRelation.setTagId(tag.getBaseId());
                customerTagRelation.setCreator(userId);
                customerTagRelation.setBaseCreateTime(new Date());
                customerTagRelations.add(customerTagRelation);
            }
            boolean saveBatchRelation = customerTagRelationService.saveBatch(customerTagRelations);
            if (! saveBatchRelation) {
                saveCustomer = false;
            }
        }
        //保存客户与协作人的关联关系
        List<String> collaborators = customerManagementDto.getCollaborators();
        if (collaborators != null && collaborators.size() > 0) {
            boolean saveBatchCollaborator = this.addCollaboratorBatch(collaborators, customerManagement.getBaseId(), userId);
            if (! saveBatchCollaborator) {
                saveCustomer = false;
            }
        }
        if (saveCustomer) {
            return Message.success("新增成功");
        } else {
            return Message.fail("新增失败");
        }
    }

    @Override
    public Message getCustomerDetails(CustomerManagementDto customerManagementDto) {
        CustomerManagementVo customerManagementVo = customerManagementMapper.selectCustomerDetails(customerManagementDto.getBaseId());
        String collaboratorsStr = customerManagementVo.getCollaborators().stream().map(CustomerCollaboratorVo::getRealname).collect(Collectors.joining(","));
        customerManagementVo.setCollaboratorsStr(collaboratorsStr);
        return Message.success(customerManagementVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message editCustomer(CustomerManagementDto customerManagementDto) {
        EnterpriseDictData enterpriseDictData = enterpriseDictDataService.getOne(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, customerManagementDto.getCompanyId())
                .eq(EnterpriseDictData::getBaseName, "潜在客户"));
        //保存客户数据
        CustomerManagement customerManagement = new CustomerManagement();
        BeanUtils.copyProperties(customerManagementDto, customerManagement);
        customerManagement.setUpdateBy(customerManagementDto.getUserId());
        customerManagement.setBaseUpdateTime(new Date());
//        String followUpState = customerManagementDto.getFollowStatus();
//        if(StringUtils.isEmpty(followUpState) && !enterpriseDictData.getBaseId().equals(customerManagementDto.getCustomerType())){
//            return Message.success("请选择跟进状态");
//        }
        CrmFollowRecordDto followUpDto = customerManagementDto.getFollowUpRecord();
        if(followUpDto != null && followUpDto.getNextFollowTime() != null){
            Date nextFollowTime = followUpDto.getNextFollowTime();
            customerManagement.setNextFollowTime(nextFollowTime);
        }
        Message message = cloudShowManagerSubService.getUserInfo(customerManagementDto.getUserId());
        if (message == null) {
            return Message.fail("获取用户信息失败！");
        }
        Object obj = message.getObj();
        if (obj == null) {
            return Message.fail("获取用户信息失败！");
        }
        if (message.getCode() == 1) {
            return Message.fail("查询用户信息错误");
        }
        ObjectMapper mapper = new ObjectMapper();
        Map resultMap = mapper.convertValue(obj, Map.class);
        String deptId = (String)resultMap.get("deptId");
        String deptName = (String)resultMap.get("deptName");
        String directorName = (String)resultMap.get("realname");
        String enterpriseId = (String)resultMap.get("companyId");
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", customerManagementDto.getUserId()));
        if(StringUtils.isEmpty(enterpriseId)){
            if(enterpriseUser != null){
                enterpriseId = enterpriseUser.getEnterpriseId();
                resultMap.put("companyId", enterpriseId);
            }else{
                return Message.fail("获取所选负责人企业信息失败！");
            }
        }
        Message validateMessage = validateInfo(customerManagementDto, enterpriseId);
        if(MessageCodeConstant.MSG_FAIL_CODE.equals(validateMessage.getCode())){
            return validateMessage;
        }

        boolean update = this.updateById(customerManagement);

        if(!enterpriseDictData.getBaseId().equals(customerManagementDto.getCustomerType())){
            addOtherInfo(customerManagement, customerManagementDto, resultMap);
        }
        //联系人
        CustomerContactsDto contact = customerManagementDto.getContact();
        if(contact != null){
            int count = customerContactsService.count(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getContactsName, contact.getContactsName()).eq(CustomerContacts::getTelephone, contact.getTelephone()).eq(CustomerContacts::getEnterpriseId, enterpriseId));
            if(count <= 0){
                //新建联系人
                CustomerContacts customerContacts = new CustomerContacts();
                BeanUtils.copyProperties(contact, customerContacts);
                customerContacts.setEnterpriseId(enterpriseId);
                customerContacts.setDeptId(deptId);
                customerContacts.setDirectorName(directorName);
                customerContacts.setDeptName(deptName);
                customerContacts.setCreator(customerManagementDto.getUserId());
                customerContacts.setBaseCreateTime(new Date());
                customerContactsService.save(customerContacts);
                CustomerContactsRelation relation = new CustomerContactsRelation();
                relation.setContactId(customerContacts.getBaseId());
                relation.setCustomerId(customerManagement.getBaseId());
                customerContactsRelationService.save(relation);
            }

        }
        List<CustomerTag> tags = customerManagementDto.getTags();
        if (tags != null && tags.size() > 0) {
            //删除历史客户与标签的关联关系
            customerTagRelationService.remove(new LambdaQueryWrapper<CustomerTagRelation>().eq(CustomerTagRelation::getCustomerId, customerManagementDto.getBaseId()));
            //保存客户与标签的关联关系
            if (tags != null && tags.size() > 0) {
                List<CustomerTagRelation> customerTagRelations = new ArrayList<>();
                for (CustomerTag tag : tags) {
                    CustomerTagRelation customerTagRelation = new CustomerTagRelation();
                    customerTagRelation.setCustomerId(customerManagement.getBaseId());
                    customerTagRelation.setTagId(tag.getBaseId());
                    customerTagRelation.setCreator(customerManagementDto.getUserId());
                    customerTagRelation.setBaseCreateTime(new Date());
                    customerTagRelations.add(customerTagRelation);
                }
                boolean saveBatchRelation = customerTagRelationService.saveBatch(customerTagRelations);
                if (! saveBatchRelation) {
                    update = false;
                }
            }
        }
        if (update) {
            return Message.success("更新成功");
        } else {
            return Message.fail("更新失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message editCustomerBatch(CustomerManagementDto customerManagementDto) {
        boolean update = true;
        List<String> updatedCustomerIds = customerManagementDto.getUpdatedCustomerIds();
        for (Map.Entry<String, Object> entry : customerManagementDto.getParamsMap().entrySet()) {
            String column = entry.getKey();
            if (StrUtil.equals(column, "tags")) {
                ObjectMapper objectMapper = new ObjectMapper();
                List<CustomerTag> tags = objectMapper.convertValue(entry.getValue(), new TypeReference<List<CustomerTag>>() {});
                if (tags != null && tags.size() > 0) {
                    //删除历史客户与标签的关联关系
                    customerTagRelationService.remove(new LambdaQueryWrapper<CustomerTagRelation>().in(CustomerTagRelation::getCustomerId, updatedCustomerIds));
                    for (String updatedCustomerId : updatedCustomerIds) {
                        List<CustomerTagRelation> customerTagRelations = new ArrayList<>();
                        for (CustomerTag tag : tags) {
                            CustomerTagRelation customerTagRelation = new CustomerTagRelation();
                            customerTagRelation.setCustomerId(updatedCustomerId);
                            customerTagRelation.setTagId(tag.getBaseId());
                            customerTagRelation.setCreator(customerManagementDto.getUserId());
                            customerTagRelation.setBaseCreateTime(new Date());
                            customerTagRelations.add(customerTagRelation);
                        }
                        boolean saveBatchRelation = customerTagRelationService.saveBatch(customerTagRelations);
                        if (! saveBatchRelation) {
                            update = false;
                        }
                    }
                    boolean updateCustomer = this.update(new UpdateWrapper<CustomerManagement>().in("base_id", updatedCustomerIds)
                            .set("update_by", customerManagementDto.getUserId())
                            .set("base_update_time", new Date()));
                    if (! updateCustomer) {
                        update = false;
                    }
                }
            } else {
                //批量更新客户实体中的数据
                update = this.update(new UpdateWrapper<CustomerManagement>().in("base_id", updatedCustomerIds)
                        .set(MyStrUtil.camelToUnderline(column).toLowerCase(), entry.getValue())
                        .set("update_by", customerManagementDto.getUserId())
                        .set("base_update_time", new Date()));
            }
        }
        if (update) {
            return Message.success("更新成功");
        } else {
            return Message.fail("更新失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message editCollaborator(CustomerManagementDto customerManagementDto) {
        String userId = customerManagementDto.getUserId();
        List<String> updatedCollaboratorIds = customerManagementDto.getUpdatedCollaboratorIds();
        List<String> updatedCustomerIds = customerManagementDto.getUpdatedCustomerIds();
        boolean isSuccess = true;
        //返回的校验信息集合
        List<String> msgList = new ArrayList<>();
        if (StrUtil.equals(customerManagementDto.getOperation(), "1")) {
            //增加协作人
            for (String updatedCustomerId : updatedCustomerIds) {
                //查询负责当前客户的相关人员（负责人以及协作人）
                //查询当前客户名称和负责人
                CustomerManagementVo customerManagement = customerManagementMapper.selectCustomerDetails(updatedCustomerId);
                String saleResponsiblePerson = customerManagement.getSaleResponsiblePerson();
                String enterpriseName = customerManagement.getEnterpriseName();

                Map<String, Map<String, String>> currentRelatedPersonnelMap = customerCollaboratorService.getRelatedPersonnelList(updatedCustomerId);
                List<String> currentRelatedPersonnel = new ArrayList<>();
                if (currentRelatedPersonnelMap != null) {
                    currentRelatedPersonnel = currentRelatedPersonnelMap.keySet().stream().collect(Collectors.toList());
                }

                List<String> updatedCollaboratorIdsCopy = new ArrayList<>(updatedCollaboratorIds);
                updatedCollaboratorIdsCopy.removeAll(currentRelatedPersonnel);
                if (updatedCollaboratorIdsCopy.size() > 0) {
                    //批量新增协作人
                    boolean saveBatch = this.addCollaboratorBatch(updatedCollaboratorIdsCopy, updatedCustomerId, userId);
                    if (! saveBatch) {
                        isSuccess = false;
                    }
                }

                if (currentRelatedPersonnelMap != null) {
                    List<String> updatedCollaboratorIdsCopy1 = new ArrayList<>(updatedCollaboratorIds);
                    updatedCollaboratorIdsCopy1.retainAll(currentRelatedPersonnel);
                    if (updatedCollaboratorIdsCopy1.size() > 0) {
                        if (updatedCollaboratorIdsCopy1.contains(saleResponsiblePerson)) {
                            msgList.add("“客户名称为：" + customerManagement.getEnterpriseName() + "所选的协作人：" + customerManagement.getSaleResponsiblePersonName() + "是客户负责人，请重新选择”");
                            updatedCollaboratorIdsCopy1.remove(saleResponsiblePerson);
                            if (updatedCollaboratorIdsCopy1.size() > 0) {
                                for (String collaboratorId : updatedCollaboratorIdsCopy1) {
                                    msgList.add("“客户名称为：" + customerManagement.getEnterpriseName() + "所选的协作人：" + currentRelatedPersonnelMap.get(collaboratorId).get("realname") + "已是协作人，请重新选择”");
                                }
                            }
                        } else {
                            for (String collaboratorId : updatedCollaboratorIdsCopy1) {
                                msgList.add("“客户名称为：" + customerManagement.getEnterpriseName() + "所选的协作人：" + currentRelatedPersonnelMap.get(collaboratorId).get("realname") + "已是协作人，请重新选择”");
                            }
                        }
                    }
                }
            }
        } else if (StrUtil.equals(customerManagementDto.getOperation(), "2")) {
            //替换协作人
            for (String updatedCustomerId : updatedCustomerIds) {
                //首先删除原有关联的协作人
                customerCollaboratorService.remove(new LambdaQueryWrapper<CustomerCollaborator>().eq(CustomerCollaborator::getCustomerId, updatedCustomerId));

                CustomerManagementVo customerManagement = customerManagementMapper.selectCustomerDetails(updatedCustomerId);
                String saleResponsiblePerson = customerManagement.getSaleResponsiblePerson();
                if (updatedCollaboratorIds.contains(saleResponsiblePerson)) {
                    msgList.add("“客户名称为：" + customerManagement.getEnterpriseName() + "所选的协作人：" + customerManagement.getSaleResponsiblePersonName() + "是客户负责人，请重新选择”");
                    updatedCollaboratorIds.remove(saleResponsiblePerson);
                }

                if (updatedCollaboratorIds.size() > 0) {
                    boolean saveBatch = this.addCollaboratorBatch(updatedCollaboratorIds, updatedCustomerId, userId);
                    if (! saveBatch) {
                        isSuccess = false;
                    }
                }
            }
        } else {
            //移除协作人
            for (String updatedCustomerId : updatedCustomerIds) {
                customerCollaboratorService.remove(new LambdaQueryWrapper<CustomerCollaborator>().eq(CustomerCollaborator::getCustomerId, updatedCustomerId)
                        .in(CustomerCollaborator::getUserId, updatedCollaboratorIds));
            }
        }
        if (isSuccess && msgList.size() == 0) {
            return Message.success("操作成功");
        } else if (isSuccess && msgList.size() > 0) {
            return Message.fail(msgList.stream().collect(Collectors.joining("，")));
        } else {
            return Message.fail("操作失败");
        }
    }

    @Override
    public Message getCollaboratorList(List<String> customerIds) {
        return Message.success(customerCollaboratorService.getCollaboratorList(customerIds));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message importCustomerBatch(MultipartFile file, String mode, String enterpriseId, String userId, String deptId, String isPublic) throws IOException {
        List<CustomerManagementExcelImport> customerManagementExcelImportList = EasyExcel.read(file.getInputStream()).head(CustomerManagementExcelImport.class).headRowNumber(6).sheet("客户").doReadSync();
        if (customerManagementExcelImportList != null && customerManagementExcelImportList.size() > 0) {
            List<String> msgList = new ArrayList<>();
            //准备要存储的数据集合
            List<CustomerManagement> customerManagements = new ArrayList<>();
//            //准备省市区的映射集
//            Map<String, Map<String, String>> areaMap = sysAreaMapper.getAreaMap();
//            //准备客户来源的映射集
//            Map<String, String> customerSourceMap = new HashMap<>();
//            customerSourceMap.put("广告", "fffdd190ca55471cbfe789f89259d63e09");
//            customerSourceMap.put("询盘", "fffdd190ca55471cbfe789f89259d63e10");
//            customerSourceMap.put("客户介绍", "fffdd190ca55471cbfe789f89259d63e11");
//            customerSourceMap.put("独立开发", "fffdd190ca55471cbfe789f89259d63e12");
//            customerSourceMap.put("社交推广", "fffdd190ca55471cbfe789f89259d63e13");
//            customerSourceMap.put("代理商", "fffdd190ca55471cbfe789f89259d63e14");
//            customerSourceMap.put("访客识别", "fffdd190ca55471cbfe789f89259d63e15");
//            customerSourceMap.put("研讨会", "fffdd190ca55471cbfe789f89259d63e16");
//            customerSourceMap.put("其他", "fffdd190ca55471cbfe789f89259d63e99");
//            //准备跟进状态的映射集
//            Map<String, String> followStatusMap = new HashMap<>();
//            followStatusMap.put("初访", "c661b397f83a4fd590f3c79ac4040dad1");
//            followStatusMap.put("意向", "c661b397f83a4fd590f3c79ac4040dad2");
//            followStatusMap.put("报价", "c661b397f83a4fd590f3c79ac4040dad3");
//            followStatusMap.put("成交", "c661b397f83a4fd590f3c79ac4040dad4");
//            followStatusMap.put("暂时搁置", "c661b397f83a4fd590f3c79ac4040dad5");
            //是否为公海内操作
            boolean isPub = StrUtil.isNotBlank(isPublic) && StrUtil.equals(isPublic, "1");
            for (CustomerManagementExcelImport customerManagementExcelImport : customerManagementExcelImportList) {
                String enterpriseName = customerManagementExcelImport.getEnterpriseName().trim();
                //查询当条数据中的客户名称是否已存在
                List<CustomerManagement> repeatedCustomerList = this.list(new LambdaQueryWrapper<CustomerManagement>()
                        .eq(CustomerManagement::getEnterpriseName, enterpriseName)
                        .eq(CustomerManagement::getCompanyId, enterpriseId));
                if (repeatedCustomerList.size() == 0) {
//                    //该条数据为当前企业的新客户数据
//                    //校验字段是否均填写正确
//                    String customerSource = customerSourceMap.get(customerManagementExcelImport.getCustomerSource());
//                    if (StrUtil.isNotBlank(customerManagementExcelImport.getCustomerSource()) && StrUtil.isBlank(customerSource)) {
//                        msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是客户来源填写有误”");
//                    } else {
//                        String followStatus = followStatusMap.get(customerManagementExcelImport.getFollowStatus());
//                        if (StrUtil.isNotBlank(customerManagementExcelImport.getFollowStatus()) && StrUtil.isBlank(followStatus)) {
//                            msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是跟进状态填写有误”");
//                        } else {
                            if (StrUtil.isBlank(customerManagementExcelImport.getContact()) && StrUtil.isNotBlank(customerManagementExcelImport.getContactPhone())) {
                                msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是联系人字段为空”");
                            } else if (StrUtil.isNotBlank(customerManagementExcelImport.getContact()) && StrUtil.isBlank(customerManagementExcelImport.getContactPhone())) {
                                msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是联系人电话字段为空”");
                            } else {
                                CustomerManagement customerManagement = new CustomerManagement();
                                customerManagement.setEnterpriseName(enterpriseName);
//                    customerManagement.setProvince(areaMap.get(customerManagementExcel.getProvince()) == null ? "" : areaMap.get(customerManagementExcel.getProvince()).get("baseId"));
//                    customerManagement.setCity(areaMap.get(customerManagementExcel.getCity()) == null ? "" : areaMap.get(customerManagementExcel.getCity()).get("baseId"));
//                    customerManagement.setCounty(areaMap.get(customerManagementExcel.getCounty()) == null ? "" : areaMap.get(customerManagementExcel.getCounty()).get("baseId"));
                                customerManagement.setLinkWayOne(customerManagementExcelImport.getLinkWayOne());
                                customerManagement.setLinkWayTwo(customerManagementExcelImport.getLinkWayTwo());
//                                customerManagement.setCustomerSource(customerSourceMap.get(customerManagementExcelImport.getCustomerSource()));
//                                customerManagement.setFollowStatus(followStatusMap.get(customerManagementExcelImport.getFollowStatus()));
//                                //对于未填写跟进状态的客户，将其客户类型自动归为潜在客户
//                                EnterpriseDictData enterpriseDictData = enterpriseDictDataService.getOne(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, enterpriseId)
//                                        .eq(EnterpriseDictData::getBaseName, "潜在客户"));
//                                if (StrUtil.isBlank(customerManagementExcelImport.getFollowStatus())) {
//                                    if (enterpriseDictData != null) {
//                                        customerManagement.setCustomerType(enterpriseDictData.getBaseId());
//                                    } else {
//                                        log.error("企业【{}】潜在客户字典项不存在，请及时处理");
//                                    }
//                                }
//                    customerManagement.setNextFollowTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(customerManagementExcel.getNextFollowTime()));
//                                Date nextFollowTime = customerManagementExcelImport.getNextFollowTime();
//                                customerManagement.setNextFollowTime(nextFollowTime == null ? null : nextFollowTime);
                                customerManagement.setCompanyId(enterpriseId);
                                customerManagement.setDeptId(isPub ? "" : deptId);
                                customerManagement.setSaleResponsiblePerson(isPub ? "" : userId);
                                if (isPub) {
                                    customerManagement.setIsPublic("1");
                                }
//                            customerManagements.add(customerManagement);
                                this.save(customerManagement);
                                if (StrUtil.isBlank(customerManagementExcelImport.getContact()) && StrUtil.isBlank(customerManagementExcelImport.getContactPhone())) {
                                    ;
                                } else {
                                    String contact = customerManagementExcelImport.getContact();
                                    String contactPhone = customerManagementExcelImport.getContactPhone();
                                    String contactPosition = customerManagementExcelImport.getContactPosition();
                                    CustomerContacts contacts = customerContactsService.getOne(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getContactsName, contact).eq(CustomerContacts::getTelephone, contactPhone).eq(CustomerContacts::getIsDelete, 0));
                                    if (contacts != null) {
                                        CustomerContactsRelation contactsRelation = CustomerContactsRelation.builder().customerId(customerManagement.getBaseId()).contactId(contacts.getBaseId()).build();
                                        customerContactsRelationService.save(contactsRelation);
                                    } else {
                                        CustomerContacts customerContacts = CustomerContacts.builder()
                                                .contactsName(contact).telephone(contactPhone).deptId(deptId)
                                                .position(contactPosition).directorId(userId).enterpriseId(enterpriseId)
                                                .creator(userId).baseCreateTime(new Date())
                                                .build();
                                        customerContactsService.save(customerContacts);
                                        CustomerContactsRelation contactsRelation = CustomerContactsRelation.builder().customerId(customerManagement.getBaseId()).contactId(customerContacts.getBaseId()).build();
                                        customerContactsRelationService.save(contactsRelation);
                                    }
                                }
                            }
//                        }
//                    }
                } else {
                    //存在重复
                    //判断是否为跨公海重复，若是，则进行提示
                    String repeatedIsPublic = repeatedCustomerList.get(0).getIsPublic();
                    if (("1".equals(isPublic) && "0".equals(repeatedIsPublic)) || (StrUtil.isBlank(isPublic) && "1".equals(repeatedIsPublic))) {
                        msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是公司已经存在相同客户名称的客户”");
                    } else {
                        //判断是哪种处理客户名称重复的模式，从而做对应的处理
                        if (StrUtil.equals(mode, "2")) {
//                            String customerSource = customerSourceMap.get(customerManagementExcelImport.getCustomerSource());
//                            if (StrUtil.isNotBlank(customerManagementExcelImport.getCustomerSource()) && StrUtil.isBlank(customerSource)) {
//                                msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是客户来源填写有误”");
//                            } else {
//                                String followStatus = followStatusMap.get(customerManagementExcelImport.getFollowStatus());
//                                if (StrUtil.isNotBlank(customerManagementExcelImport.getFollowStatus()) && StrUtil.isBlank(followStatus)) {
//                                    msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是跟进状态填写有误”");
//                                } else {
                                    if (StrUtil.isBlank(customerManagementExcelImport.getContact()) && StrUtil.isNotBlank(customerManagementExcelImport.getContactPhone())) {
                                        msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是联系人字段为空”");
                                    } else if (StrUtil.isNotBlank(customerManagementExcelImport.getContact()) && StrUtil.isBlank(customerManagementExcelImport.getContactPhone())) {
                                        msgList.add("“客户名称为：" + enterpriseName + "导入失败，原因是联系人电话字段为空”");
                                    } else {
                                        //覆盖导入
                                        CustomerManagement customerManagement = new CustomerManagement();
                                        customerManagement.setBaseId(repeatedCustomerList.get(0).getBaseId());
//                        customerManagement.setProvince(areaMap.get(customerManagementExcel.getProvince()) == null ? "" : areaMap.get(customerManagementExcel.getProvince()).get("baseId"));
//                        customerManagement.setCity(areaMap.get(customerManagementExcel.getCity()) == null ? "" : areaMap.get(customerManagementExcel.getCity()).get("baseId"));
//                        customerManagement.setCounty(areaMap.get(customerManagementExcel.getCounty()) == null ? "" : areaMap.get(customerManagementExcel.getCounty()).get("baseId"));
                                        customerManagement.setLinkWayOne(customerManagementExcelImport.getLinkWayOne());
                                        customerManagement.setLinkWayTwo(customerManagementExcelImport.getLinkWayTwo());
//                                        customerManagement.setCustomerSource(customerSourceMap.get(customerManagementExcelImport.getCustomerSource()));
//                                        customerManagement.setFollowStatus(followStatusMap.get(customerManagementExcelImport.getFollowStatus()));
//                                        //对于未填写跟进状态的客户，将其客户类型自动归为潜在客户
//                                        EnterpriseDictData enterpriseDictData = enterpriseDictDataService.getOne(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, enterpriseId)
//                                                .eq(EnterpriseDictData::getBaseName, "潜在客户"));
//                                        if (StrUtil.isBlank(customerManagementExcelImport.getFollowStatus())) {
//                                            if (enterpriseDictData != null) {
//                                                customerManagement.setCustomerType(enterpriseDictData.getBaseId());
//                                            } else {
//                                                log.error("企业【{}】潜在客户字典项不存在，请及时处理");
//                                            }
//                                        }
//                        customerManagement.setNextFollowTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(customerManagementExcel.getNextFollowTime()));
//                                        Date nextFollowTime = customerManagementExcelImport.getNextFollowTime();
//                                        customerManagement.setNextFollowTime(nextFollowTime == null ? null : nextFollowTime);
                                        customerManagement.setCompanyId(enterpriseId);
                                        customerManagement.setDeptId(isPub ? "" : deptId);
                                        customerManagement.setSaleResponsiblePerson(isPub ? "" : userId);
                                        if (isPub) {
                                            customerManagement.setIsPublic("1");
                                        }
//                                    customerManagements.add(customerManagement);
                                        this.updateById(customerManagement);
//                                    不能删除相应的联系人因为联系人可能还关联着其他的客户
//                                    List<String> contactIds = customerContactsRelationService.list(new LambdaQueryWrapper<CustomerContactsRelation>().eq(CustomerContactsRelation::getCustomerId, customerManagement.getBaseId())).stream().map(CustomerContactsRelation::getContactId).collect(Collectors.toList());
//                                    customerContactsService.remove(new LambdaQueryWrapper<CustomerContacts>().in(CustomerContacts::getBaseId, contactIds));
                                        customerContactsRelationService.remove(new LambdaQueryWrapper<CustomerContactsRelation>().eq(CustomerContactsRelation::getCustomerId, customerManagement.getBaseId()));
                                        String contact = customerManagementExcelImport.getContact();
                                        String contactPhone = customerManagementExcelImport.getContactPhone();
                                        String contactPosition = customerManagementExcelImport.getContactPosition();
                                        if (StrUtil.isBlank(contact) && StrUtil.isBlank(contactPhone)) {
                                            CustomerContacts contacts = customerContactsService.getOne(new LambdaQueryWrapper<CustomerContacts>().eq(CustomerContacts::getContactsName, contact).eq(CustomerContacts::getTelephone, contactPhone).eq(CustomerContacts::getIsDelete, 0));
                                            if (contacts != null) {
                                                CustomerContactsRelation contactsRelation = CustomerContactsRelation.builder().customerId(customerManagement.getBaseId()).contactId(contacts.getBaseId()).build();
                                                customerContactsRelationService.save(contactsRelation);
                                            } else {
                                                CustomerContacts customerContacts = CustomerContacts.builder()
                                                        .contactsName(contact).telephone(contactPhone).deptId(deptId)
                                                        .position(contactPosition).directorId(userId).enterpriseId(enterpriseId)
                                                        .creator(userId).baseCreateTime(new Date())
                                                        .build();
                                                customerContactsService.save(customerContacts);
                                                CustomerContactsRelation contactsRelation = CustomerContactsRelation.builder().customerId(customerManagement.getBaseId()).contactId(customerContacts.getBaseId()).build();
                                                customerContactsRelationService.save(contactsRelation);
                                            }
                                        }
                                    }
//                                }
//                            }
                        } else {
                            //mode == '1' 不导入
                            ;
                        }
                    }
                }
            }
//            if (customerManagements.size() > 0) {
//                boolean saveOrUpdateBatch = this.saveOrUpdateBatch(customerManagements);
//                if (saveOrUpdateBatch && msgList.size() == 0) {
//                    return Message.success("导入成功");
//                } else if (saveOrUpdateBatch && msgList.size() > 0){
//                    return Message.fail(msgList.stream().collect(Collectors.joining("，")));
//                } else {
//                    return Message.fail("导入失败，原因是网络异常，请稍后重试");
//                }
//            } else if (customerManagements.size() == 0 && (msgList.size() > 0)){
//                return Message.fail(msgList.stream().collect(Collectors.joining("，")));
//            } else {
//                return Message.success("导入成功");
//            }

            if (msgList.size() == 0) {
                return Message.success("导入成功");
            } else if (msgList.size() > 0){
                return Message.fail(msgList.stream().collect(Collectors.joining("，")));
            } else {
                return Message.fail("导入失败，原因是网络异常，请稍后重试");
            }
        } else {
            return Message.fail("导入失败，原因是未读取到表格内数据");
        }
    }

    /**
     * 批量新增客户的协作人
     * @param collaboratorUserIds 要新增的协作人用户ID集合
     * @param customerId 客户ID
     * @param userId 操作人用户ID
     */
    private boolean addCollaboratorBatch(List<String> collaboratorUserIds, String customerId, String userId) {
        List<CustomerCollaborator> customerCollaborators = new ArrayList<>();
        for (String collaboratorUserId : collaboratorUserIds) {
            CustomerCollaborator customerCollaborator = new CustomerCollaborator();
            customerCollaborator.setCustomerId(customerId);
            customerCollaborator.setUserId(collaboratorUserId);
            customerCollaborator.setCreator(userId);
            customerCollaborator.setBaseCreateTime(new Date());
            customerCollaborators.add(customerCollaborator);
        }
        return customerCollaboratorService.saveBatch(customerCollaborators);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message updateContact(CustomerManagementDto customerManagementDto) {
        String baseId = customerManagementDto.getBaseId();
        //解除当前客户与原有联系人之间的关联关系
        customerContactsRelationService.remove(new LambdaQueryWrapper<CustomerContactsRelation>().eq(CustomerContactsRelation::getCustomerId, baseId));
        //创建新的联系人关联关系
        boolean res = true;
        List<String> contactIds = customerManagementDto.getContactIds();
        if (contactIds.size() > 0) {
            ArrayList<CustomerContactsRelation> customerContactsRelations = new ArrayList<>();
            for (String contactId : contactIds) {
                CustomerContactsRelation customerContactsRelation = new CustomerContactsRelation();
                customerContactsRelation.setCustomerId(baseId);
                customerContactsRelation.setContactId(contactId);
                customerContactsRelations.add(customerContactsRelation);
            }
            boolean saveBatch = customerContactsRelationService.saveBatch(customerContactsRelations);
            if (! saveBatch) {
                res = false;
            }
        }
        if (res) {
            return Message.success("修改成功");
        } else {
            return Message.fail("修改失败");
        }
    }

    @Override
    public Message getFollowListByCustomerId(String customerId) {
        List<CrmFollowRecord> list = crmFollowRecordService.getListByCustomerId(customerId);
        return Message.success(list);
    }

    private Message validateInfo(CustomerManagementDto customerManagementDto, String enterpriseId){
        CommunicateInfoSaveDto business = customerManagementDto.getBusiness();
        if(business != null){
            String businessName = business.getProductName();
            //查询商机名称是否存在
            long businessCount = communicateInfoService.count(new LambdaQueryWrapper<CommunicateInfo>().eq(CommunicateInfo::getProductName, businessName).eq(CommunicateInfo::getCompanyId, enterpriseId));
            if(businessCount > 0){
                return Message.fail("商机标题已存在！");
            }
            List<String> collactorIdList = business.getCollaboratorIdList();
            String directorId = customerManagementDto.getUserId();
            if(!CollectionUtils.isEmpty(collactorIdList) && !StringUtils.isEmpty(directorId) && collactorIdList.contains(directorId)){
                return Message.fail("协作人不能包含负责人");
            }
        }
        //查询合同名称是否存在
        CardBusinessContractDto contract = customerManagementDto.getContract();
        if(contract != null){
            long contractCount = cardBusinessContractService.count(new LambdaQueryWrapper<CardBusinessContract>().eq(CardBusinessContract::getBaseName, contract.getBaseName()).eq(CardBusinessContract::getEnterpriseId, enterpriseId));
            if(contractCount > 0){
                return Message.fail("合同名称已存在！");
            }
        }

        return Message.success();
    }

    private void addOtherInfo(CustomerManagement customerManagement, CustomerManagementDto customerManagementDto, Map userMap){
        String deptId = (String)userMap.get("deptId");
        String deptName = (String)userMap.get("deptName");
        String directorName = (String)userMap.get("realname");
        String enterpriseId = (String)userMap.get("companyId");
        String userId = customerManagementDto.getUserId();
        CommunicateInfoSaveDto business = customerManagementDto.getBusiness();
        if(business != null){
            business.setCustomerId(customerManagement.getBaseId());
            CommunicateInfo communicateInfo = new CommunicateInfo();
            LuLianEnterprise enterprise = enterpriseService.getById(enterpriseId);
            BeanUtils.copyProperties(business,communicateInfo);
            communicateInfo.setCompanyName(enterprise.getBaseName());
            communicateInfo.setDeptId(deptId);
            communicateInfo.setDirectorId(userId);
            communicateInfo.setDirectorName(directorName);
            communicateInfo.setCompanyId(enterpriseId);
            communicateInfo.setCreator(customerManagementDto.getUserId());
            communicateInfo.setBaseCreateTime(new Date());
            communicateInfoService.save(communicateInfo);
            List<String> collactorIdList = business.getCollaboratorIdList();
            if(!CollectionUtils.isEmpty(collactorIdList)){
                String collactorIds = String.join(",", collactorIdList);
                Message userMessage = cloudShowManagerSubService.getUserList(collactorIds);
                if(userMessage == null || userMessage.getCode() == 1){
                    throw new RuntimeException("员工信息获取失败");
                }

                List<LinkedHashMap> userInfoList = (List<LinkedHashMap>)userMessage.getObj();
                if(userInfoList != null && !userInfoList.isEmpty()){
                    Map<Object, LinkedHashMap> usersMap = userInfoList.stream().collect(Collectors.toMap(k ->
                                    k.get("baseId"),
                            v -> v,
                            (existing, replacement) -> existing
                    ));
                    List collactorList = new ArrayList();
                    for (String collactorId : collactorIdList) {
                        LinkedHashMap map = usersMap.get(collactorId);
                        CardBusinessCollaborator cardBusinessCollaborator = new CardBusinessCollaborator();
                        cardBusinessCollaborator.setCompanyId(communicateInfo.getCompanyId());
                        cardBusinessCollaborator.setUserId(collactorId);
                        cardBusinessCollaborator.setRelateId(communicateInfo.getBaseId());
                        cardBusinessCollaborator.setUserName(map.get("realname") == null ? "" : map.get("realname").toString());
                        cardBusinessCollaborator.setDeptId(map.get("deptId") == null ? "" : map.get("deptId").toString());
                        collactorList.add(cardBusinessCollaborator);
                    }
                    if(!CollectionUtils.isEmpty(collactorList)){
                        cardBusinessCollaboratorService.saveBatch(collactorList);
                    }
                }


            }
        }
        CardBusinessContractDto contract = customerManagementDto.getContract();
        if(contract != null){
            contract.setCustomerId(customerManagement.getBaseId());
            CardBusinessContract cardBusinessContract = new CardBusinessContract();
            BeanUtils.copyProperties(contract,cardBusinessContract);
            cardBusinessContract.setDeptId(deptId);
            cardBusinessContract.setDeptName(deptName);
            cardBusinessContract.setDirectorId(userId);
            cardBusinessContract.setDirectorName(directorName);
            cardBusinessContract.setBaseCreateName(directorName);
            cardBusinessContract.setEnterpriseId(enterpriseId);
            cardBusinessContract.setBaseCreateBy(customerManagementDto.getUserId());
            cardBusinessContract.setBaseCreateTime(new Date());
            cardBusinessContractService.save(cardBusinessContract);
        }
        //新建跟进记录
        //若当前跟进对象为客户类型，同时往原客户跟进记录表中存储一份数据
        String customerId = customerManagement.getBaseId();
        CrmFollowRecordDto followUpRecord = customerManagementDto.getFollowUpRecord();
        if(followUpRecord != null){
            CrmFollowRecord crmFollowRecord = new CrmFollowRecord();
            BeanUtils.copyProperties(followUpRecord,crmFollowRecord);
            crmFollowRecord.setCreator(customerManagementDto.getUserId());
            crmFollowRecord.setBaseCreateTime(new Date());
            crmFollowRecord.setObjectId(customerId);
            crmFollowRecordService.save(crmFollowRecord);
            CustomerFollowUpRecord customerFollowUpRecord = CustomerFollowUpRecord.builder()
                    .followUpType(crmFollowRecord.getFollowType())
                    .followUpTime(crmFollowRecord.getPracticalFollowTime())
                    .content(crmFollowRecord.getContent())
                    .customerId(customerId)
                    .followUpState(crmFollowRecord.getStatus())
                    .linkMan(crmFollowRecord.getLinkman())
                    .nextFollowUpTime(crmFollowRecord.getNextFollowTime())
                    .recordType("1")
                    .enterpriseId(crmFollowRecord.getEnterpriseId())
                    .baseCreateBy(customerManagementDto.getUserId())
                    .baseCreateTime(new Date())
                    .baseUpdateTime(new Date())
                    .cfrId(crmFollowRecord.getBaseId())
                    .followUpState(crmFollowRecord.getStatus())
                    .build();
            customerFollowUpRecordMapper.insert(customerFollowUpRecord);
//            Date nextFollowUpTime = crmFollowRecord.getNextFollowTime();
//            if(nextFollowUpTime != null){
//                customerManagement.setNextFollowTime(nextFollowUpTime);
//                this.updateById(customerManagement);
//            }


        }

    }

//    private void getOtherInfo(CustomerManagementVo customerManagementVo, String customerId){
//        List<CardBusinessContract> contractList = cardBusinessContractService.list(new LambdaQueryWrapper<CardBusinessContract>().eq(CardBusinessContract::getCustomerId, customerId));
//        if(!CollectionUtils.isEmpty(contractList)){
//            CardBusinessContract cardBusinessContract = contractList.get(0);
//            String baseId = cardBusinessContract.getBaseId();
//            Message message = cardBusinessContractService.detailInfo(baseId);
//            if(MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())){
//                CardBusinessContractVo contractVo = (CardBusinessContractVo)message.getObj();
//                customerManagementVo.setContract(contractVo);
//            }
//        }
//        List<CommunicateInfo> communicateInfoList = communicateInfoService.list(new LambdaQueryWrapper<CommunicateInfo>().eq(CommunicateInfo::getCustomerId, customerId));
//        if(!CollectionUtils.isEmpty(communicateInfoList)){
//            CommunicateInfo info = communicateInfoList.get(0);
//            String baseId = info.getBaseId();
//            Message message = communicateInfoService.detailInfo(baseId);
//            if(MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())){
//                CommunicateInfoVo vo = (CommunicateInfoVo)message.getObj();
//                customerManagementVo.setBusiness(vo);
//            }
//        }
//        List<CrmFollowRecord> vo = crmFollowRecordService.getListByCustomerId(customerId);
//
//
//
//    }
}